<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="addPermission(1, '0')"
          >添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button
                v-if="scope.row.type === 1"
                type="text"
                @click="addPermission(2, scope.row.id)"
              >添加</el-button>
              <el-button
                type="text"
                @click="editPer(scope.row.id)"
              >编辑</el-button>
              <el-button
                type="text"
                @click="delPer(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog
          :title="isEdit ? '编辑权限点' : '新增权限点'"
          :visible="showDialog"
          @close="btnCancel"
        >
          <!-- 表单 -->
          <el-form
            ref="perForm"
            :model="formData"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width: 90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button
                size="small"
                type="primary"
                @click="addPer"
              >确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { tranListToTreeData } from '@/utils'
import {
  getPermissionList,
  addPermission,
  getPermissionDetail,
  updatePermission,
  delPermission
} from '@/api/permission'
export default {
  name: 'Permisson',
  data() {
    // 验证权限 名称 是否重复
    const validName = (rule, value, callback) => {
      // 新增时验证
      // 先找到兄弟节点 只要pid一致
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      // 将兄弟节点的name 组成新数组 再用 includes 进行验证输入的value

      if (this.isEdit) {
        //  在编辑时验证是把本身排除 pid相同 id不同
        existNameList = this.originList
          .filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }

      // 新增时验证是否重复

      existNameList
        .map(item => item.name.trim())
        .includes(value) ? callback(new Error(`权限名称 ${value} 已存在`)) : callback()
    }

    // 验证权限 标识 是否重复
    const validCode = (rule, value, callback) => {
      let existCodeList = this.originList
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }

      // 新增时 验证是否重复
      existCodeList
        .map(item => item.code)
        .includes(value) ? callback(new Error(`权限标识 ${value} 已存在`)) : callback()
    }
    return {
      permissionList: [], // 权限列表
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      isEdit: false, // 是否是编辑
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取权限列表方法
    this.getPermissionList()
  },
  methods: {
    // 点击删除按钮 删除对应id的列表
    async delPer(id) {
      const confirm = await this.$confirm('您确定要删除此权限吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirm === 'cancel') return this.$message('您取消了删除')

      const res = await delPermission(id)
      this.$message.success(res.message)
      this.getPermissionList()
    },

    // 编辑功能
    async editPer(id) {
      const res = await getPermissionDetail(id)
      // 反向赋值,显示数据
      this.formData = res.data
      // 是编辑 为true
      this.isEdit = true
      // 显示弹框
      this.showDialog = true
    },

    // 点击确定按钮事件
    addPer() {
      // 兜底验证
      this.$refs.perForm.validate(async(valid) => {
        // 失败直接return
        if (!valid) return
        // 成功 调接口
        if (!this.isEdit) {
          const res = await addPermission(this.formData)
          // console.log(res)
          // 提示用户 关闭弹框 刷新列表
          this.$message.success(res.message)
        } else {
          const res = await updatePermission(this.formData)
          this.$message.success(res.message)
        }
        this.showDialog = false
        this.getPermissionList()
      })
    },

    // 添加权限功能
    addPermission(type, id) {
      this.formData.type = type
      this.formData.pid = id
      this.isEdit = false
      this.showDialog = true
    },

    // 点击取消功能
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // console.log(123)
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },

    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      console.log(res)

      // 将自定义验证函数使用的数据进行精简
      this.originList = res.data.map((item) => ({
        id: item.id,
        pid: item.pid,
        name: item.name,
        code: item.code
      }))

      this.permissionList = tranListToTreeData(res.data)
    }
  }
}
</script>

<style lang="scss" scoped></style>
